package kr.hkit.powerjava.chapter18;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;

public class Panel_JTable extends JPanel implements ActionListener {
	private JTable table;
	private JButton btnAdd;

	/**
	 * Create the panel.
	 */
	public Panel_JTable() {

		initialize();
		tableCellAlginAndWidth(); //정렬용 메소드
	}
	
	
	private void tableCellAlginAndWidth() { //외우셔야됩니다.
		//가운데정렬
		DefaultTableCellRenderer dtcrCenter = new DefaultTableCellRenderer();
		dtcrCenter.setHorizontalAlignment(SwingConstants.CENTER);
		
		//우측 정렬
		DefaultTableCellRenderer dtcrRight = new DefaultTableCellRenderer();
		dtcrRight.setHorizontalAlignment(SwingConstants.RIGHT);
		
		//컬럼의 개수 가져오기위해
		TableColumnModel cModel = table.getColumnModel();
		
		int columnCount = cModel.getColumnCount(); //컬럼의 개수 
		//int로 받은거는 반복문 쓸때 쓰면됨
		
		//일괄적용할려면 반복문 쓰기
		cModel.getColumn(0).setPreferredWidth(70); //사이즈 옆 간격
		cModel.getColumn(0).setCellRenderer(dtcrCenter); //가운데 정렬
		
		cModel.getColumn(1).setPreferredWidth(70); //사이즈 옆 간격
		cModel.getColumn(1).setCellRenderer(dtcrCenter); //가운데 정렬
		
		cModel.getColumn(2).setPreferredWidth(70); //사이즈 옆 간격
		cModel.getColumn(2).setCellRenderer(dtcrCenter); //가운데 정렬
		
		cModel.getColumn(3).setPreferredWidth(70); //사이즈 옆 간격
		cModel.getColumn(3).setCellRenderer(dtcrCenter); //가운데 정렬
		
		cModel.getColumn(4).setPreferredWidth(150); //사이즈 옆 간격
		cModel.getColumn(4).setCellRenderer(dtcrRight); //가운데 정렬
		
		cModel.getColumn(5).setPreferredWidth(70); //사이즈 옆 간격
		cModel.getColumn(5).setCellRenderer(dtcrCenter); //가운데 정렬
		
		
	}


	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel_Top = new JPanel();
		add(panel_Top, BorderLayout.NORTH);
		
		btnAdd = new JButton("추가");
		btnAdd.addActionListener(this);
		panel_Top.add(btnAdd);
		
		JPanel panel_Bottom = new JPanel();
		add(panel_Bottom, BorderLayout.SOUTH);
		
		final JLabel lblSelected = new JLabel("New label");
		panel_Bottom.add(lblSelected);
		
		JScrollPane scrollPane = new JScrollPane();
		add(scrollPane, BorderLayout.CENTER);
		
		String[] colNames = {"사원번호", "사원명", "직책", "매니저", "급여", "부서번호"};
		
		TableModel model = new DefaultTableModel(colNames, 0){ //getColumnClass 오버라이드

			
			@Override
			public Class<?> getColumnClass(int columnIndex) { //첫번째 컬럼의 타입 지정.
				return getValueAt(0, columnIndex).getClass(); //이거 했기 때문에 숫자는 오른쪽, 문자는 왼쪽정렬됨
			}
		};
		
		table = new JTable(model);
		table.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				
				int row = table.getSelectedRow();
				int col = table.getSelectedColumn();
				try{
					String text = (String) table.getModel().getValueAt(row, col);
					lblSelected.setText(text);
				} catch (ClassCastException e1) {
					int value = (int) table.getModel().getValueAt(row, col);
					lblSelected.setText(value+"");
				}
			
				
				//모든 레코드값이 출력되도록 해보자
				StringBuilder sb = new StringBuilder();
				for (int i =0; i < table.getColumnCount(); i++) {
					sb.append(table.getModel().getValueAt(row, i)+" ");
				}
				lblSelected.setText(sb.toString());
			}
		});
		
		table.setAutoCreateRowSorter(true); //속성이름 누르면 그 순으로 정렬됩니다.
		scrollPane.setViewportView(table);
		
	}
	
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnAdd) {
			actionPerformedBtnAdd(e);
		}
	}

	protected void actionPerformedBtnAdd(ActionEvent e) {
		DecimalFormat df = new DecimalFormat("#,###"); //급여 포멧 
		
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		// 타입이 각각 다르므로 object로 만듬
		Object[] newRow = { new Integer((int) (Math.random() * 100) + 1),
				"김태희", "사원", new Integer((int) (Math.random() * 100) + 1),
				df.format(new Integer((int) (Math.random() * 10000000) + 1)),
				new Integer((int) (Math.random() * 10) + 1) 
		};
		
		model.addRow(newRow);
		
	}
}
